package com.guigu.ssyx.acl.service.impl;

import com.atguigu.ssyx.model.acl.Permission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.guigu.ssyx.acl.helper.PermissionHelper;
import com.guigu.ssyx.acl.service.PermissionService;
import com.guigu.ssyx.acl.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author 代奉明
* @description 针对表【permission(权限)】的数据库操作Service实现
* @createDate 2025-09-04 09:28:39
*/
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
    implements PermissionService{

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public List<Permission> queryAllMenu() {
        LambdaQueryWrapper<Permission> permissionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        permissionLambdaQueryWrapper.orderByAsc(Permission::getId);
        List<Permission> allPerssionList = permissionMapper.selectList(permissionLambdaQueryWrapper);


        //把权限数据构建成树形结构
        List<Permission> permissionList = PermissionHelper.build(allPerssionList);


        return permissionList;
    }

    /**
     * 递归删除id
     * */
    @Override
    public void removeChildById(Long id) {
        ArrayList<Long> idList = new ArrayList<>();
        this.getAllPermissionId(id, idList);
        idList.add(id);
        permissionMapper.deleteBatchIds(idList);


    }
    /**
     * 递归获取子节点id
     * */
    private void getAllPermissionId(Long id, ArrayList<Long> idList) {
        LambdaQueryWrapper<Permission> permissionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        permissionLambdaQueryWrapper.eq(Permission::getPid, id).select(Permission::getId);

        List<Permission> childList = permissionMapper.selectList(permissionLambdaQueryWrapper);
        childList.stream().forEach(item -> {
            idList.add(item.getId());
            this.getAllPermissionId(item.getId(), idList);
        });
    }
}




